package com.codeoss.framework.workflow.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.expression.Expression;
import com.codeoss.framework.expression.IScriptServiceStore;
import com.codeoss.framework.workflow.context.WorkflowContext;
import com.codeoss.framework.workflow.def.DecisionNodeDef;
import com.codeoss.framework.workflow.def.LineDef;
import com.codeoss.framework.workflow.def.WorkflowDef;
import com.codeoss.framework.workflow.store.IWorkflowStore;

@Service
public class DecisionNodeService extends AbstractNodeService {
	@Autowired
    private IScriptServiceStore scriptServiceStore;
	@Autowired
	private IWorkflowStore workflowStore;
	@Override
	@Transactional
	public void execute(WorkflowContext workflowContext) {
		// TODO Auto-generated method stub
		DecisionNodeDef decisionNodeDef=(DecisionNodeDef)workflowContext.getNodeDef();
		Map<String,Object> bindingMap=new HashMap<String,Object>();
		bindingMap.put("workflowContext", workflowContext);
		bindingMap.put("approved", workflowContext.getApproved());
		Expression expression=decisionNodeDef.getDecisionExpression();
		if(expression!=null) {
			String transitionName=(String)scriptServiceStore.getScriptService(expression).eval(expression.getScript(), bindingMap);
			end(workflowContext, transitionName);
			return;
		}
		
		Long workflowWorkflowId=workflowContext.getWorkflowProcess().getWorkflowWorkflowId();
		WorkflowDef workflowDef=workflowStore.get(workflowWorkflowId);
		List<LineDef> lineList=workflowDef.getLineList();
		for(int i=0;i<lineList.size();i++) {
			LineDef lineDef=lineList.get(i);
			if(lineDef.getFromNodeId().equals(decisionNodeDef.getId())) {
				Expression conditionExpression=lineDef.getCondition();
				if(conditionExpression==null) {
					end(workflowContext, lineDef.getName());
					return;
				}else {
					boolean result=(boolean)scriptServiceStore.getScriptService(conditionExpression).eval(conditionExpression.getScript(), bindingMap);
					if(result) {
						end(workflowContext, lineDef.getName());
						return;
					}
				}
			}
		}
	}
}
